package com.cjm.juc.wanwenjun;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 这里就是使用到了stamp， 版本的意思， 解决的是ABA的问题
 */
public class AtomicIntegerTest {
    private static AtomicInteger atomicRef = new AtomicInteger(100);

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                atomicRef.compareAndSet(100, 101);
                System.err.println("after one value = " + atomicRef.get());
                TimeUnit.SECONDS.sleep(1);
                atomicRef.compareAndSet(101, 102);
                System.err.println("after two value = " + atomicRef.get());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "cjm-juc-atomicReference");

        thread.start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Thread thread1 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                atomicRef.compareAndSet(102, 100);
                System.err.println("after three value = " + atomicRef.get());
                TimeUnit.SECONDS.sleep(1);
                boolean b = atomicRef.compareAndSet(100, 104);
                System.err.println("after four value = " + atomicRef.get() + ";update success : " + b);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "cjm-juc-atomicReference");

        thread1.start();
    }
}
